package com.studyroom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.studyroom.entity.Feedback;
import com.studyroom.entity.User;
import com.studyroom.exception.ServiceException;
import com.studyroom.mapper.FeedbackMapper;
import com.studyroom.service.FeedbackService;
import com.studyroom.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.studyroom.mapper.UserMapper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;

@Service
public class FeedbackServiceImpl extends ServiceImpl<FeedbackMapper, Feedback> implements FeedbackService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DataSource dataSource;

    @Override
    public void submit(String username, Feedback feedback) {
        User user = userService.getUserByUsername(username);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        
        // 获取当前时间并格式化为字符串
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        
        feedback.setUserId(user.getId());
        feedback.setStatus(0);  // 设置为未处理
        feedback.setCreatedAt(now);
        feedback.setUpdatedAt(now);
        
        save(feedback);
    }

    @Override
    public Page<Feedback> getMyFeedback(String username, Integer page, Integer size) {
        User user = userService.getUserByUsername(username);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        
        LambdaQueryWrapper<Feedback> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Feedback::getUserId, user.getId())
               .orderByDesc(Feedback::getCreatedAt);
        
        return page(new Page<>(page, size), wrapper);
    }

    @Override
    public Feedback getDetail(String username, Long id) {
        User user = userService.getUserByUsername(username);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        
        LambdaQueryWrapper<Feedback> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Feedback::getId, id)
               .eq(Feedback::getUserId, user.getId());
        
        Feedback feedback = getOne(wrapper);
        if (feedback == null) {
            throw new ServiceException("反馈不存在或无权查看");
        }
        
        return feedback;
    }

    @Override
    public void reply(Long id, String reply) {
        // 更新反馈
        Feedback feedback = getById(id);
        if (feedback == null) {
            throw new RuntimeException("反馈不存在");
        }
        
        // 获取当前时间并格式化为字符串
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        
        feedback.setReply(reply);
        feedback.setStatus(1); // 设置为已处理
        feedback.setUpdatedAt(now);
        
        updateById(feedback);
    }

    @Override
    public IPage<Feedback> getFeedbackPage(Page<Feedback> page, String content, Integer status) {
        // 创建一个新的分页对象
        Page<Feedback> result = new Page<>(page.getCurrent(), page.getSize());
        List<Feedback> records = new ArrayList<>();
        
        // 构建手动 SQL 查询
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT f.*, u.username ")
           .append("FROM feedbacks f ")
           .append("LEFT JOIN users u ON f.user_id = u.id ")
           .append("WHERE 1=1 ");
        
        List<Object> params = new ArrayList<>();
        
        if (StringUtils.hasText(content)) {
            sql.append("AND f.content LIKE ? ");
            params.add("%" + content + "%");
        }
        
        if (status != null) {
            sql.append("AND f.status = ? ");
            params.add(status);
        }
        
        sql.append("ORDER BY f.created_at DESC ");
        
        // 使用 jdbcTemplate 执行查询
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql.toString(),
                     ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) {
            
            // 设置参数
            for (int i = 0; i < params.size(); i++) {
                stmt.setObject(i + 1, params.get(i));
            }
            
            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    Feedback feedback = new Feedback();
                    feedback.setId(rs.getLong("id"));
                    feedback.setUserId(rs.getLong("user_id"));
                    feedback.setContent(rs.getString("content"));
                    feedback.setReply(rs.getString("reply"));
                    feedback.setStatus(rs.getInt("status"));
                    feedback.setImages(rs.getString("images"));
                    feedback.setCreatedAt(rs.getString("created_at"));
                    feedback.setUpdatedAt(rs.getString("updated_at"));
                    feedback.setUsername(rs.getString("username"));
                    records.add(feedback);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("执行SQL查询失败", e);
        }
        
        // 设置结果
        result.setRecords(records);
        result.setTotal(countTotal(content, status));
        
        return result;
    }

    private long countTotal(String content, Integer status) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT COUNT(*) FROM feedbacks f WHERE 1=1 ");
        
        List<Object> params = new ArrayList<>();
        
        if (StringUtils.hasText(content)) {
            sql.append("AND f.content LIKE ? ");
            params.add("%" + content + "%");
        }
        
        if (status != null) {
            sql.append("AND f.status = ? ");
            params.add(status);
        }
        
        // 使用 jdbcTemplate 执行查询
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql.toString())) {
            
            // 设置参数
            for (int i = 0; i < params.size(); i++) {
                stmt.setObject(i + 1, params.get(i));
            }
            
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return rs.getLong(1);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("执行计数SQL查询失败", e);
        }
        
        return 0;
    }

    @Override
    public Page<Feedback> getAdminFeedbackList(Integer current, Integer size, String content, Integer status) {
        // 创建一个新的分页对象
        Page<Feedback> result = new Page<>(current, size);
        List<Feedback> records = new ArrayList<>();
        
        // 构建手动 SQL 查询
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT f.*, u.username ")
           .append("FROM feedbacks f ")
           .append("LEFT JOIN users u ON f.user_id = u.id ")
           .append("WHERE 1=1 ");
        
        List<Object> params = new ArrayList<>();
        
        if (StringUtils.hasText(content)) {
            sql.append("AND f.content LIKE ? ");
            params.add("%" + content + "%");
        }
        
        if (status != null) {
            sql.append("AND f.status = ? ");
            params.add(status);
        }
        
        sql.append("ORDER BY f.created_at DESC ")
           .append("LIMIT ? OFFSET ?");
        
        params.add(size);
        params.add((current - 1) * size);
        
        // 使用 JDBC 执行查询
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql.toString())) {
            
            // 设置参数
            for (int i = 0; i < params.size(); i++) {
                stmt.setObject(i + 1, params.get(i));
            }
            
            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    Feedback feedback = new Feedback();
                    feedback.setId(rs.getLong("id"));
                    feedback.setUserId(rs.getLong("user_id"));
                    feedback.setContent(rs.getString("content"));
                    feedback.setReply(rs.getString("reply"));
                    feedback.setStatus(rs.getInt("status"));
                    feedback.setImages(rs.getString("images"));
                    feedback.setCreatedAt(rs.getString("created_at"));
                    feedback.setUpdatedAt(rs.getString("updated_at"));
                    feedback.setUsername(rs.getString("username"));
                    records.add(feedback);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("执行SQL查询失败", e);
        }
        
        // 设置结果
        result.setRecords(records);
        result.setTotal(countTotal(content, status));
        
        return result;
    }

    @Override
    public boolean deleteFeedback(Long id) {
        // 获取反馈信息
        Feedback feedback = this.getById(id);
        if (feedback == null) {
            throw new RuntimeException("留言不存在");
        }
        
        // 删除反馈
        return this.removeById(id);
    }
} 